<template>
  <div v-loading="tableLoading" class="evaluate" :style="{ overflow: 'auto', height: windowHeight + 'px' }">
    <div class="evaluate-bottom list-div flex mt20">
      <el-tree :data="treeLeftTitle" :props="defaultProps" default-expand-all :expand-on-click-node="false">
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <span :class="'level' + data.level" :style="{ color: data.color ? data.color : '' }">{{ node.label }}</span>
        </span>
      </el-tree>
      <div class="flex evaluate-li" style="overflow: auto;">
        <div v-for="(item, index) in treeRightNum" :key="index" class="flex flex-border">
          <div v-for="(info, ind) in item.arrs" :key="ind" class="flex-item">
            <span class="info info-tit">{{ info.tit }}</span>
            <div class="item-val">
              <div v-for="(ele, inds) in info.arr" :key="inds" class="info info-li" :class="setClass(info.arr, inds, ele)">
                <span v-if="ele.type === 'radio'">
                  {{ percentageCalculation(info.arr, inds) + '%' }}
                </span>
                <span v-else>
                  <!-- :disabled="(ele.disabled || (ele.type === 'es' && ele.originalVal !== undefined && ele.originalVal !== null && ele.originalVal !== '' && ele.originalVal !== '0' && ele.originalVal !== 0) || index === 1)" -->
                  <Money
                    v-if="ele.type === 'act' || ele.type === 'es'"
                    v-model="ele.val"
                    :disabled="treeRightNum.length > 1 ? (index === 1) : false"
                    :class="ele.disabled ? 'notBorderToInputColor' : 'notBorderToInput'"
                    :placeholder="$t('指标值')"
                    @change="doubleBindData($event, ele, info.tit)"
                  />
                  <span v-else>
                    {{ moneyFormat(ele.val) }}
                  </span>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 审核按钮 -->
    <div style="z-index: 2001;text-align: center;height: 50px;width: 100%;background: white;box-shadow: rgb(0 0 0 / 0%) 0 3px 12px 2px;">
      <el-button v-if="auditStatus" type="primary" @click="submitFromSave('staging')">{{ $t('暂存') }}</el-button>
      <el-button v-if="auditStatus" type="primary" @click="submitForm('save')">{{ $t('提交') }}</el-button>
    </div>
  </div>
</template>
<script>
import { getDealIndicatorDataMain, getAllData, listDealIndicatorPredictKey, interfaceSaveDetail, listDealIndicatorDataDetailOut } from '@/api/deal/indicator/data/dealIndicatorDataDetail.js'
import { getSysFormCache } from '@/api/sys/formCache/sysFormCache'
export default {
  name: 'LeaderEvaluate',
  components: {
  },
  data() {
    return {
      // 表格左侧树
      treeLeftTitle: [],
      // 右侧表格中的数据
      treeRightNum: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表格部分的遮盖层
      tableLoading: false,
      // "预测数据维护" 页面中主表的信息
      dealIndicatorPredictData: {},
      // 审核状态
      auditStatus: true,
      indicatorIdByUrl: this.$route.query.id,
      currencyCompanyId: undefined,
      // 已填写并提交的报告期
      submittedReportPeriod: [],
      windowHeight: 650
    }
  },
  computed: {
  },
  created() {
    // 获取当前窗口高度
    this.windowHeight = window.innerHeight
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.initTable()
    },
    initTable() {
      // 初始化table
      this.tableLoading = true
      getDealIndicatorDataMain(this.indicatorIdByUrl).then(response => {
        if (response.data !== null) {
          this.dealIndicatorPredictData = response.data
          // 检查提交按钮
          if (this.dealIndicatorPredictData.status === '已复核' || this.dealIndicatorPredictData.status === '待复核') {
            this.auditStatus = false
          }
          // 获取历史提交记录
          getSysFormCache(this.$route.query.cacheId).then(response2 => {
            if (response2.data !== null && response2.data.cacheValue !== null) {
              const cacheValue = JSON.parse(response2.data.cacheValue)
              this.submittedReportPeriod = cacheValue.editList
            }
            // 初始化Table
            this.initializeTable(this.dealIndicatorPredictData.id)
          })
        } else {
          this.msgWarning(this.$t('无可填写数据,请联系管理员确认!'))
        }
      })
    },
    /**
     * 初始化表格 入口
     */
    initializeTable(id) {
      this.treeLeftTitle = [{ label: this.$t('指标'), level: 1, children: [] }]
      // 获取该项目下配置的预测指标
      getAllData({ parentId: '0', businessId: id }).then(response => {
        // 整理数据. 符合tree的要求
        this.getTableLeftTreeUpData(response.rows, undefined)
        // 获取关键指标 该项目下的
        listDealIndicatorPredictKey({ businessId: this.currencyCompanyId }).then(() => {
          // 整理数据, 符合tree的要求
          // -------------------------------------------------------------
          // this.getTableLeftTreeUpData(undefined, response.data)
          // -------------------------------------------------------------
          // 加载右边的table
          listDealIndicatorDataDetailOut({ parentId: this.dealIndicatorPredictData.id }).then(response => {
            this.getTableRightData(response.rows)
            this.tableLoading = false
          })
        })
      })
    },
    /**
     * 初始化表格 左侧树加载
     */
    getTableLeftTreeUpData(indicatorListTemp, indicatorPredictKey) {
      if (indicatorListTemp !== undefined && indicatorListTemp !== null) {
        indicatorListTemp && indicatorListTemp.forEach(item => {
          var children = []
          var count = 0
          item.children && item.children.forEach((item2, index2) => {
            children[count++] = { id: item2.id, label: item2.indicators + '-EST', type: 'YJ', indicatorType: 'yy', color: '#5a5a5a' }
            children[count++] = { id: item2.id, label: item2.indicators + '-ACT', type: 'SJ', indicatorType: 'yy', color: '#5a5a5a' }
            children[count++] = { id: item2.id, label: this.$t('完成比例') + '-(%)', type: 'ratio', indicatorType: 'yy', color: '#5a5a5a' }
            if (index2 + 1 !== item.children.length) {
              children[count++] = { label: '' }
            }
          })
          this.treeLeftTitle[0].children.push({ id: item.id, label: item.indicators, indicatorType: 'yy', children: children, color: '#5a5a5a' })
        })
      }
      if (indicatorPredictKey !== undefined && indicatorPredictKey !== null) {
        indicatorPredictKey && indicatorPredictKey.forEach(item => {
          var children = item.children
          children && children.forEach((item2, index2) => {
            children[index2] = { id: item2.id, label: item2.keyName, indicatorType: 'gj', color: '#00ceff' }
          })
          this.treeLeftTitle[0].children.push({ id: item.id, label: item.keyReport, indicatorType: 'gj', children: children, color: '#00ceff' })
        })
      }
    },
    /**
     * 初始化表格 右侧表格初始化 (设计思路以月为基准)
     *    排列方式固定.  都是以 年/ 季度 / 月  排序
     *    如果选择的周期为季度. 那么月就展示出来了.
     */
    getTableRightData(tableData) {
      // 数据准备
      this.treeRightNum = []
      const startYear = Number(this.dealIndicatorPredictData.startYear)
      const forecastYear = Number(this.dealIndicatorPredictData.forecastYear)
      const cycle = this.dealIndicatorPredictData.cycle
      // 1. 先将表格 按年季度月展示出来
      var y = 0
      var q = 0
      var m = 0
      var yearArr = []
      var quarterArr = []
      var monthArr = []

      // 年
      for (y = startYear; y < (startYear + forecastYear); y++) {
        yearArr.push({ tit: y, arr: [{ val: undefined, type: undefined }] })
      }
      // 补充表格的空数据
      this.autoFillTable(yearArr, true, false)
      this.treeRightNum.push({ arrs: yearArr })

      // 季度
      if (cycle === 'quarter' || cycle === 'month') {
        for (y = startYear; y < (startYear + forecastYear); y++) {
          for (q = 1; q <= 4; q++) {
            quarterArr.push({ tit: y + '-Q' + q, arr: [{ val: undefined, type: undefined }] })
          }
        }
        // 补充表格的空数据
        this.autoFillTable(quarterArr, true, false)
        this.treeRightNum.push({ arrs: quarterArr })
      }

      // 月份
      if (cycle === 'month') {
        for (y = startYear; y < (startYear + forecastYear); y++) {
          for (m = 1; m <= 12; m++) {
            monthArr.push({ tit: y + '-' + m, arr: [{ val: undefined, type: undefined }] })
          }
        }
        // 补充表格的空数据
        this.autoFillTable(monthArr, true, false)
        this.treeRightNum.push({ arrs: monthArr })
      }

      // -------------------------------------------------------------
      // 将上月/上季度/上年的要填写的数据 列在第一列
      var temps = []
      if (cycle === 'year') {
        var tempYearArr = []
        this.submittedReportPeriod && this.submittedReportPeriod.forEach(item => {
          tempYearArr.push({ tit: item, arr: [{ val: undefined, type: undefined }] })
        })
        this.autoFillTable(tempYearArr, false, true)
        temps.push({ arrs: tempYearArr })
        temps.push(this.treeRightNum[0])
      }
      if (cycle === 'quarter') {
        var tempQuarterArr = []
        this.submittedReportPeriod && this.submittedReportPeriod.forEach(item => {
          tempQuarterArr.push({ tit: item, arr: [{ val: undefined, type: undefined }] })
        })
        this.autoFillTable(tempQuarterArr, false, true)
        temps.push({ arrs: tempQuarterArr })
        temps.push(this.treeRightNum[1])
      }
      if (cycle === 'month') {
        var tempMonthArr = []
        this.submittedReportPeriod && this.submittedReportPeriod.forEach(item => {
          var title = item.split('-')
          tempMonthArr.push({ tit: title[0] + '-' + parseInt(title[1]), arr: [{ val: undefined, type: undefined }] })
        })
        this.autoFillTable(tempMonthArr, false, true)
        temps.push({ arrs: tempMonthArr })
        temps.push(this.treeRightNum[2])
      }
      console.log(temps)
      var showTable = []
      showTable = temps
      if (temps.length >= 2) {
        if (temps[0].arrs.length === temps[1].arrs.length) {
          showTable = []
          showTable.push(temps[0])
        }
      }
      this.treeRightNum = showTable

      // 2. 将设置好的测值对号入座, 如果没有填写预测值, 那么默认为0
      this.takeASeatAccordingToTheNumber(tableData, cycle)
    },
    /**
     * 安排好左侧的树以后.  需要自动设置好右侧对应的表格. (设置的表格都是空表格)
     * @param data
     * @param disabled
     * @param isFirstColumn
     */
    autoFillTable(data, disabled, isFirstColumn) {
      const yy = this.treeLeftTitle && this.treeLeftTitle[0]
      if (yy) {
        yy.children.forEach((itemObj, index) => {
          if (index > 0) {
            data.forEach(column => { column.arr.push({ val: undefined, type: undefined }) })
          }
          var itemTemp2Arr = itemObj ? itemObj.children : {}
          itemTemp2Arr && itemTemp2Arr.forEach((item) => {
            if (item.label.substring(item.label.lastIndexOf('-') + 1) === 'EST' && item.indicatorType === 'yy') {
              data.forEach(column => { column.arr.push({ val: undefined, type: 'es', indicatorId: item.id, indicatorType: 'YJ', isFirstColumn: isFirstColumn }) })
            } else if (item.label.substring(item.label.lastIndexOf('-') + 1) === 'ACT' && item.indicatorType === 'yy') {
              data.forEach(column => { column.arr.push({ val: undefined, type: 'act', indicatorId: item.id, indicatorType: 'SJ', disabled: disabled, isFirstColumn: isFirstColumn }) })
            } else if (item.label.substring(item.label.lastIndexOf('-') + 1) === '(%)' && item.indicatorType === 'yy') {
              data.forEach(column => { column.arr.push({ val: undefined, type: 'radio', indicatorId: item.id, indicatorType: 'ratio', isFirstColumn: isFirstColumn }) })
            } else if (item.indicatorType === 'gj') {
              data.forEach(column => { column.arr.push({ val: undefined, type: 'radio', indicatorId: item.id, isFirstColumn: isFirstColumn }) })
            } else {
              data.forEach(column => { column.arr.push({ val: undefined, type: undefined, isFirstColumn: isFirstColumn }) })
            }
          })
        })
      }
    },
    /**
     * 后台取出的值对号入座
     */
    takeASeatAccordingToTheNumber(tableData, cycle) {
      if (tableData !== undefined && tableData !== null && tableData.length > 0) {
        tableData.forEach(item => {
          this.treeRightNum.forEach(itemNumOne => {
            itemNumOne.arrs && itemNumOne.arrs.forEach(itemTwo => {
              var title = itemTwo.tit
              title = title ? title.toString().split('-') : ''
              itemTwo.arr && itemTwo.arr.forEach(itemThree => {
                if (cycle === 'year') {
                  if (title[0] === item.year && item.indicatorId === itemThree.indicatorId) {
                    if (itemThree.indicatorType === 'YJ' && item.dataType === 'YJ') {
                      itemThree.val = item.value
                      itemThree.originalVal = item.value
                    }
                    if (itemThree.indicatorType === 'SJ' && item.dataType === 'SJ') {
                      itemThree.val = item.value
                      itemThree.originalVal = item.value
                    }
                  }
                }
                if (cycle === 'quarter') {
                  var quarter = title[1] ? title[1].replace('Q', '') : ''
                  if (title[0] === item.year && quarter === item.quarter && item.indicatorId === itemThree.indicatorId) {
                    if (itemThree.indicatorType === 'YJ' && item.dataType === 'YJ') {
                      itemThree.val = item.value
                      itemThree.originalVal = item.value
                    }
                    if (itemThree.indicatorType === 'SJ' && item.dataType === 'SJ') {
                      itemThree.val = item.value
                      itemThree.originalVal = item.value
                    }
                  }
                }
                if (cycle === 'month') {
                  if (title[0] === item.year && title[1] === item.month && item.indicatorId === itemThree.indicatorId) {
                    if (itemThree.indicatorType === 'YJ' && item.dataType === 'YJ') {
                      itemThree.val = item.value
                      itemThree.originalVal = item.value
                    }
                    if (itemThree.indicatorType === 'SJ' && item.dataType === 'SJ') {
                      itemThree.val = item.value
                      itemThree.originalVal = item.value
                    }
                  }
                }
              })
            })
          })
        })
      }
    },
    itemClasses(data) {
      var result = []
      while (result.length < 3) {
        result.push('score-item')
      }
      for (let i = 0; i < result.length; i++) {
        if (i < data) {
          var sclass = ''
          if (data < 2) {
            sclass = 'low'
          }
          if (data === 2) {
            sclass = 'middle'
          }
          if (data > 2) {
            sclass = 'high'
          }
          result[i] = result[i] + ' ' + sclass
        }
      }
      return result
    },
    setClass(data, index, ele) {
      if (ele.type === 'es') {
        return 'es'
      }
      if (ele.type === 'act') {
        return 'act'
      }
      if (ele.type === 'radio') {
        if (this.percentageCalculation(data, index) >= 100) {
          return 'positive'
        } else if (this.percentageCalculation(data, index) === 0) {
          return 'moneyEmpty'
        } else {
          return 'negative'
        }
      }
    },
    /**
     * 百分比计算
     * @param data
     * @param index
     * @param ele
     * @returns {string|number|*}
     */
    percentageCalculation(data, index) {
      const temp = ((parseFloat(data[index - 1].val) / parseFloat(data[index - 2].val)) * 100).toFixed(2)
      return isNaN(Number(temp)) ? 0 : (temp === 'Infinity' ? 0 : temp)
    },
    /**
     * 首列数据与主体中的数据双向绑定
     */
    doubleBindData(value, ele, tit) {
      this.treeRightNum.forEach((one) => {
        one.arrs.forEach(two => {
          two.arr.forEach((three) => {
            if (two.tit === tit) {
              if (ele.type === 'act' && ele.indicatorType === 'SJ' && three.type === 'act' && ele.indicatorType === 'SJ' && ele.indicatorId === three.indicatorId) {
                ele.val = value
                three.val = value
              }
              if (ele.type === 'es' && ele.indicatorType === 'YJ' && three.type === 'es' && ele.indicatorType === 'YJ' && ele.indicatorId === three.indicatorId) {
                ele.val = value
                three.val = value
              }
            }
          })
        })
      })
    },
    /**
     * 提交
     */
    submitForm(saveType) {
      var _this = this
      this.$confirm(this.$t('是否确认提交?'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        _this.submitFromSave(saveType)
      }).catch(() => {
      })
    },
    submitFromSave(saveType) {
      this.tableLoading = true
      const cycle = this.dealIndicatorPredictData.cycle
      var result = []
      if (cycle === 'year') {
        this.treeRightNum.forEach(one => {
          one.arrs.forEach(item => {
            item.arr && item.arr.forEach(item2 => {
              item2.value = item2.val
              if ((item2.indicatorType === 'SJ' || item2.indicatorType === 'YJ') && item2 && item2.value !== 0) {
                item2.year = item.tit
                item2.dataType = item2.indicatorType
                result.push(item2)
              }
            })
          })
        })
      } else if (cycle === 'quarter') {
        // ------------------------------------------------ this.treeRightNum[1].arrs.forEach(item => {
        this.treeRightNum.forEach(one => {
          one.arrs.forEach(item => {
          // ------------------------------------------------
          var title = item.tit.split('-')
          var yearTemp = title[0]
          var quarterTemp = title[1].replace('Q', '')
          item.arr && item.arr.forEach(item2 => {
            item2.value = item2.val
            if ((item2.indicatorType === 'SJ' || item2.indicatorType === 'YJ') && item2 && item2.value !== 0) {
              item2.year = yearTemp
              item2.quarter = quarterTemp
              item2.dataType = item2.indicatorType
              result.push(item2)
            }
          })
        })
      })
      } else if (cycle === 'month') {
        // ------------------------------------------------ this.treeRightNum[2].arrs.forEach(item => {
        this.treeRightNum.forEach(one => {
          one.arrs.forEach(item => {
            // ------------------------------------------------
            var title = item.tit.split('-')
            var yearTemp = title[0]
            var monthTemp = title[1].replace('Q', '')
            item.arr && item.arr.forEach(item2 => {
              item2.value = item2.val
              if ((item2.indicatorType === 'SJ' || item2.indicatorType === 'YJ') && item2.value !== undefined && item2.value !== 0) {
                item2.year = yearTemp
                item2.month = monthTemp
                item2.dataType = item2.indicatorType
                result.push(item2)
              }
            })
          })
        })
      }
      if (result.length <= 0) {
        this.msgError(this.$t('请先填写数据!'))
        this.tableLoading = false
      } else {
        interfaceSaveDetail({
          dealId: this.dealIndicatorPredictData.dealId,
          id: this.dealIndicatorPredictData.id,
          dealIndicatorDataDetailList: result,
          cycle: this.dealIndicatorPredictData.cycle,
          reportList: this.submittedReportPeriod,
          saveStatus: saveType
        }).then(() => {
          this.msgSuccess(this.$t('提交成功'))
          this.initTable()
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.es {
  background: rgba(0, 0, 0, 0.15);
}

.act {
  background: #4CAFEA;
}

.positive {
  background: #88C184;
}

.moneyEmpty {
  border: 1px solid #f1f1f1;
}

.negative {
  background: #E7726F;
}

.mt20 {
  margin-top: 20px;
}

.flex {
  display: flex;
  align-items: center;
}

.flex1 {
  flex: 1;
}

.evaluate-tit {
  color: #43437C;
  font-size: 14px;
  font-weight: bold;
  margin: 0;
}

.list-div {
  padding: 15px;
  box-shadow: 0 3px 12px 2px rgba(0, 0, 0, 0.08);
  background-color: #FFF;
  color: #303133;
  -webkit-transition: .3s;
  transition: .3s;
  border-radius: 4px;
  font-size: 14px;
}

.evaluate {
  &-top {
    display: flex;
    column-gap: 20px;
    line-height: 20px;

    .list-div {
      flex: 1;

      .des {
        margin: 10px 0;
        height: 100px;
        display: -webkit-box; /*弹性伸缩盒子*/
        -webkit-box-orient: vertical; /*垂直排列*/
        line-clamp: 5;
        -webkit-line-clamp: 5; /*只显示6行*/
        overflow: hidden; /*溢出隐藏*/
        text-overflow: ellipsis; /*省略号代替*/
      }

      .score {
        display: flex;
        column-gap: 2px;

        span {
          display: block;
          height: 6px;
          flex: 1;
          background: #F5F6FB;

          &:first-child {
            border-radius: 5px 0 0 5px;
          }

          &:last-child {
            border-radius: 0 5px 5px 0;
          }
        }

        .high {
          background: #3DCC5D;
        }

        .middle {
          background: #FDB029;
        }

        .low {
          background: #FC5230;
        }
      }
    }
  }

  &-historical {
    column-gap: 20px;
    padding-top: 35px;

    .content {
      max-width: 90%;
      flex: 1;
      display: flex;
      // background: #F5F6FB;
    }
  }
}

.historical-list {
  position: relative;
  white-space: nowrap;
  background: #F5F6FB;
  padding: 5px 20px;

  .line-item {
    column-gap: 1px;
    position: absolute;
    top: -20px;

    span {
      height: 17px;
      display: block;
      width: 8px;
      border-radius: 10px;
      background: #34CB56;
    }

    .on {
      background: #FDB12D;
    }
  }
}

.chart-select {
  width: 150px;

  /deep/ .el-input__inner {
    background-color: #DDDEF2;
    border: 0;
    color: #393974;
    border-radius: 20px;
  }

  /deep/ .el-input__suffix {
    color: #393974;
  }
}

.evaluate-bottom {
  /deep/ .el-tree-node__content {
    height: 30px;
  }

  /deep/ .el-tree-node__content:hover {
    background-color: transparent !important;
  }
}

/deep/ .el-tree {
  color: #42437C;

  .level1 {
    font-size: 15px;
    font-weight: 600;
  }

  .level2 {
    font-size: 14px;
    font-weight: 500;
  }
}

.evaluate-li {
  margin-left: 20px;
  overflow: auto;

  .info {
    height: 30px;
    display: block;
    line-height: 30px;
    min-width: 100px;
    text-align: center;
  }

  .info-tit {
    background: #F5F6FB;
    color: #42437C;
    font-weight: bold;
    border-right: 1px solid #fff;
  }

  .flex-border {
    border: 1px solid #E7EAF5;
    margin-right: 5px;

    .flex-item {
      &:last-child {
        .info-tit {
          border: 0 !important;
        }
      }
    }
  }
}

.h1-time {
  color: #8a8a8a;
  font-size: 14px;
  margin-left: 10px;
}

/deep/ .dialogForm .el-dialog__body {
  overflow: auto;
}
.notBorderToInput >>> .el-input__inner {
  -webkit-appearance: none;
  background-image: none;
  color: black;
  width: 100%;
  border-radius: 0 !important;
  text-align: center;
}
.notBorderToInputColor >>> .el-input__inner {
  background: #f1f1f1 ;
  -webkit-appearance: none;
  color: black;
  width: 100%;
  border-radius: 0 !important;
  text-align: center;
}
.audit-btn {
  width: 45px;
  height: 45px;
  position: absolute;
  right: 20px;
  cursor: pointer;
  user-select: none;
  z-index: 2003;
  font-size: 14px;
  border: 1px solid #5a5a5a;
  border-radius: 30px;
  line-height: 3;
  text-align: center;
  color: white;
  background: #5a5a5a;
}
/deep/ .el-tree-node__expand-icon.expanded {
  display: none;
}
</style>
